<template>
  <div class="app-container">
    <el-card>
      <div slot="header">
        <span>{{ title }}</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回列表</el-button>
      </div>
      
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库名称" prop="warehouseName">
              <el-input v-model="form.warehouseName" placeholder="请输入仓库名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属园区" prop="parkId">
              <el-select
                v-model="form.parkId"
                placeholder="请选择所属园区"
                clearable
                filterable
                :loading="optionsLoading"
                style="width: 100%"
              >
                <el-option
                  v-for="item in parkOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库类型" prop="warehouseType">
              <el-select
                v-model="form.warehouseType"
                placeholder="请选择仓库类型"
                clearable
                filterable
                :loading="optionsLoading"
                style="width: 100%"
              >
                <el-option
                  v-for="item in warehouseTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
        <el-form-item label="仓库行业" prop="industryDataId">
          <el-select
            v-model="form.industryDataId"
            placeholder="请选择仓库行业"
            clearable
            filterable
            :loading="optionsLoading"
            style="width: 100%"
          >
            <el-option
              v-for="item in industryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="是否推荐到首页" prop="isRecommend">
              <div class="recommend-switch">
              <el-switch
                v-model="form.isRecommend"
                :active-value="1"
                :inactive-value="0"
                active-text="推荐"
                inactive-text="不推荐"
                        active-color="#67C23A"
                      inactive-color="#F56C6C"
                    />
                    <span class="switch-tip">{{ form.isRecommend === 1 ? '该仓库将在首页推荐列表中显示' : '该仓库不会在首页推荐列表中显示' }}</span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="仓库描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入仓库描述" />
        </el-form-item>

        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="地址补充说明" prop="addressDesc">
          <el-input v-model="form.addressDesc" placeholder="请输入地址补充说明(如：距地铁站100米)" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="库房面积" prop="areaSize">
              <el-input v-model="form.areaSize" placeholder="请输入库房面积">
                <template slot="append">m²</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="地面承重" prop="floorLoad">
              <el-input v-model="form.floorLoad" placeholder="请输入地面承重">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="月台数量" prop="platformCount">
              <el-input v-model="form.platformCount" placeholder="请输入月台数量">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="出租单价" prop="rentalPrice">
              <el-input v-model="form.rentalPrice" placeholder="请输入出租单价">
                <template slot="append">元/m²</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="装卸设备配置" prop="equipmentConfig">
          <el-input v-model="form.equipmentConfig" placeholder="请输入装卸设备配置" />
        </el-form-item>

        <el-form-item label="仓库配置" prop="hardwareConfig">
          <el-input 
            v-model="form.hardwareConfig" 
            placeholder="请输入硬件配置，输入多个以，分隔" 
            type="textarea"
            :rows="3"
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="消防等级" prop="fireLevel">
              <el-input v-model="form.fireLevel" placeholder="请输入消防等级" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="消防设施" prop="fireFacilities">
              <el-input v-model="form.fireFacilities" placeholder="请输入消防设施" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="安保配置" prop="security">
          <el-input v-model="form.security" placeholder="请输入安保配置" />
        </el-form-item>

        <el-form-item label="增值服务" prop="additionalServices">
          <el-input 
            v-model="form.additionalServices" 
            placeholder="请输入增值服务，输入多个以，分隔" 
            type="textarea"
            :rows="3"
          />
        </el-form-item>

        <el-form-item label="仓库标签" prop="warehouseTags">
          <el-select
            v-model="form.warehouseTags"
            multiple
            filterable
            clearable
            placeholder="请选择仓库标签"
            :loading="optionsLoading"
            style="width: 100%"
          >
            <el-option
              v-for="item in tagOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="VR全景链接" prop="vrLink">
          <el-input v-model="form.vrLink" placeholder="请输入VR全景链接" />
        </el-form-item>

        <el-form-item label="Banner页面" prop="bannerPage">
          <el-select
            v-model="form.bannerPage"
            placeholder="请选择Banner页面"
            clearable
            filterable
            :loading="optionsLoading"
            style="width: 100%"
          >
            <el-option
              v-for="(item, index) in bannerPageOptions"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="缩略图" prop="thumbnailUrl">
          <EditImage
            v-model="form.thumbnailUrl"
            :cropper-config="{
              autoCrop: true,
              autoCropWidth: 640,
              autoCropHeight: 480,
              fixedBox: false,
              outputType: 'png'
            }"
            :dialog-width="'800px'"
            :cropper-height="400"
            upload-tip="支持 JPG、PNG 格式，建议尺寸 640x480，文件大小不超过 5MB"
            placeholder-text="请上传仓库缩略图，建议尺寸 640x480 像素"
            cropper-title="仓库图片裁剪"
            :max-file-size="5"
            @image-cropped="onImageCropped"
            @image-removed="onImageRemoved"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="goBack">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getWarehouse, addWarehouse, updateWarehouse, uploadWarehouseFile } from "@/api/system/warehouse"
import { listPark } from "@/api/system/park"
import { listPark_tags } from "@/api/system/park_tags"
import { listWarehouse_type } from "@/api/system/warehouse_type"
import { listBannerPage } from "@/api/system/banner"
import EditImage from '@/components/EditImage/EditImage.vue'
import { VueCropper } from "vue-cropper"
import { debounce } from '@/utils'
import { BASE_FILE_URL, BASE_API } from '@/utils/constants'

export default {
  name: "WarehouseAdd",
  components: { EditImage },
  data() {
    return {
      // 弹出层标题
      title: "",
      BASE_API: BASE_API, // 添加BASE_API到data中
      // 表单参数
      form: {
        warehouseId: null,
        warehouseName: null,
        description: null,
        address: null,
        parkId: null,
        warehouseType: null,
        areaSize: null,
        floorLoad: null,
        platformCount: null,
        rentalPrice: null,
        equipmentConfig: null,
        hardwareConfig: null,
        fireLevel: null,
        fireFacilities: null,
        security: null,
        additionalServices: null,
        warehouseTags: [],
        industryDataId: null, // 修改：使用industryDataId字段
        addressDesc: null,
        vrLink: null,
        bannerPage: null,
        thumbnailUrl: null,
        isRecommend: 1
      },
      // 表单校验
      rules: {
        warehouseName: [
          { required: true, message: "仓库名称不能为空", trigger: "blur" }
        ],
        address: [
          { required: true, message: "详细地址不能为空", trigger: "blur" }
        ],
        parkId: [
          { required: true, message: "所属园区不能为空", trigger: "blur" }
        ],
        warehouseType: [
          { required: true, message: "仓库类型不能为空", trigger: "blur" }
        ],
        industryDataId: [
          { required: true, message: "仓库行业不能为空", trigger: "blur" }
        ],
        areaSize: [
          { required: true, message: "库房面积不能为空", trigger: "blur" }
        ],
        floorLoad: [
          { required: true, message: "地面承重不能为空", trigger: "blur" }
        ],
        rentalPrice: [
          { required: true, message: "出租单价不能为空", trigger: "blur" },
          { pattern: /^[0-9]\d*(\.\d{1,2})?$/, message: "出租单价必须为正数，最多保留两位小数", trigger: "blur" }
        ],
      },
      // 下拉选项数据
      parkOptions: [],
      tagOptions: [],
      industryOptions: [], // 新增：行业数据选项
      warehouseTypeOptions: [],
      bannerPageOptions: [],
      optionsLoading: false,
      // 图片裁剪相关
      croppedImageBlob: null
    }
  },
  async created() {
    await this.getOptions()
    this.initForm()
  },
  methods: {
    /** 初始化表单 */
    initForm() {
      const { id } = this.$route.query
      if (id) {
        // 编辑模式
        this.title = "修改仓库基础信息"
        this.getWarehouseData(id)
      } else {
        // 新增模式
        this.title = "添加仓库基础信息"
        this.reset()
      }
    },
    /** 获取仓库数据 */
    getWarehouseData(id) {
      getWarehouse(id).then(response => {
        this.form = response.data
        
        // 处理标签数据：从对象数组提取ID值
        if (Array.isArray(this.form.warehouseTags)) {
          this.form.warehouseTags = this.form.warehouseTags.map(item => item.tagId || item.id);
        } else if (typeof this.form.warehouseTags === 'string') {
          this.form.warehouseTags = this.form.warehouseTags.split(',').filter(Boolean);
        } else {
          this.form.warehouseTags = [];
        }
        this.form.parkId = this.form.parkInfo.parkId;
        // 处理仓库类型：如果是对象，提取typeId值
        if (this.form.warehouseType && typeof this.form.warehouseType === 'object') {
          this.form.warehouseType = this.form.warehouseType.typeId || this.form.warehouseType.id;
        }
      })
    },
    /** 获取下拉选项数据 */
    async getOptions() {
      if (this.optionsLoading) return; // 防止重复加载
      
      this.optionsLoading = true;
      try {
        // 并行请求下拉选项数据
        const [parkRes, tagRes, industryRes, typeRes, bannerPageRes] = await Promise.all([
          listPark(),
          listPark_tags({tagType: 1}),
          listPark_tags({tagType: 2}),
          listWarehouse_type(),
          listBannerPage()
        ]);

        // 处理园区选项
        const parkData = parkRes.rows || parkRes.data || parkRes;
        this.parkOptions = Array.isArray(parkData) ? parkData : [];
        this.parkOptions = this.parkOptions.map(item => ({
          label: item.parkName || item.label || item.name,
          value: item.parkId || item.value || item.id
        }));

        // 处理标签选项
        const tagData = tagRes.rows;
        this.tagOptions = Array.isArray(tagData) ? tagData : [];
        this.tagOptions = this.tagOptions.map(item => ({
          label: item.tagName || item.label || item.name,
          value: item.tagId || item.value || item.id
        }));

        // 处理行业数据选项
        const industryData = industryRes.rows;
        this.industryOptions = Array.isArray(industryData) ? industryData : [];
        this.industryOptions = this.industryOptions.map(item => ({
          label: item.tagName || item.label || item.name,
          value: item.tagId || item.value || item.id // 确保value是tagId
        }));

        // 处理仓库类型选项
        const typeData = typeRes.rows || typeRes.data || typeRes;
        this.warehouseTypeOptions = Array.isArray(typeData) ? typeData : [];
        this.warehouseTypeOptions = this.warehouseTypeOptions.map(item => ({
          label: item.typeName || item.label || item.name,
          value: item.typeId || item.value || item.id
        }));

        // 处理Banner页面选项
        const bannerPageData = bannerPageRes.rows || bannerPageRes.data || bannerPageRes;
        this.bannerPageOptions = Array.isArray(bannerPageData) ? bannerPageData : [];

      } catch (error) {
        console.error('获取下拉选项数据失败:', error);
      } finally {
        this.optionsLoading = false;
      }
    },
    /** 拼接服务器图片地址 */
    getFullImageUrl(imageUrl) {
      if (!imageUrl) return '';
      // 如果已经是http/https/base64开头，直接返回
      if (/^(http|https):\/\//.test(imageUrl) || imageUrl.startsWith('data:image/')) {
        return imageUrl;
      }
      // 兼容斜杠
      if (imageUrl.startsWith('/')) {
        return this.BASE_API + imageUrl;
      }
      // 默认拼接文件服务器路径
      return BASE_FILE_URL + imageUrl;
    },
    // 表单重置
    reset() {
      this.form = {
        warehouseId: null,
        warehouseName: null,
        description: null,
        address: null,
        parkId: null,
        warehouseType: null,
        areaSize: null,
        floorLoad: null,
        platformCount: null,
        rentalPrice: null,
        equipmentConfig: null,
        hardwareConfig: null,
        fireLevel: null,
        fireFacilities: null,
        security: null,
        additionalServices: null,
        warehouseTags: [],
        industryDataId: null, // 修改：重置为null
        addressDesc: null,
        vrLink: null,
        bannerPage: null,
        thumbnailUrl: null,
        isRecommend: 1
      }
      this.croppedImageBlob = null // 新增：重置裁剪图片
      this.resetForm("form")
    },
    /** 返回列表 */
    goBack() {
      this.$router.back()
    },
    /** 提交按钮 */
    async submitForm() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          // 创建表单数据副本，避免修改原始表单数据
          const submitData = { ...this.form }

          // 替换 hardwareConfig 和 additionalServices 字段中的中文逗号为英文逗号
          if (typeof submitData.hardwareConfig === 'string') {
            submitData.hardwareConfig = submitData.hardwareConfig.replace(/，/g, ',')
          }
          if (typeof submitData.additionalServices === 'string') {
            submitData.additionalServices = submitData.additionalServices.replace(/，/g, ',')
          }

          // 处理图片上传（新增或修改时）
          if (this.croppedImageBlob) {
            // 有裁剪后的图片blob，先上传图片
            try {
              const formData = new FormData()
              formData.append('file', this.croppedImageBlob, 'warehouse.png')
              formData.append('type', 1) // 新增：上传时带上type=1参数
              const res = await uploadWarehouseFile(formData)
              if (res && res.code === 200 && res.fileName) {
                submitData.thumbnailUrl = res.fileName || res.url // 兼容返回格式
              } else {
                this.$modal.msgError("图片上传失败1")
                return
              }
            } catch (e) {
              this.$modal.msgError("图片上传失败2")
              return
            }
          }
        
          // 处理多选标签：转为后端需要的对象数组 [{ tagId }]
          if (Array.isArray(submitData.warehouseTags)) {
            submitData.warehouseTags = submitData.warehouseTags.map(id => ({ tagId: id }))
          }
          
          // 处理仓库类型：如果是对象，提取typeId值
          if (submitData.warehouseType && typeof submitData.warehouseType === 'object') {
            submitData.warehouseType = submitData.warehouseType.typeId || submitData.warehouseType.id
          }

          // 处理行业数据：直接使用tagId，不需要转换格式
          // 因为industryDataId本身就是tagId，直接提交即可
          // 如果后端需要特定格式，可以在这里转换

          if (submitData.warehouseId != null) {
            updateWarehouse(submitData).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.goBack()
            })
          } else {
            addWarehouse(submitData).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.goBack()
            })
          }
        }
      })
    },
    // EditImage组件回调方法
    onImageCropped(blob, base64Url) {
      this.croppedImageBlob = blob
      console.log('图片裁剪完成:', blob, base64Url)
    },
    onImageRemoved() {
      this.croppedImageBlob = null
      console.log('图片已删除')
    }
  }
}
</script>

<style scoped lang="scss">
 .recommend-switch {
        display: flex;
        align-items: center;
        gap: 12px;
        
        .switch-tip {
          font-size: 12px;
          color: #909399;
          flex: 1;
        }
      }
</style>